package com.jajahome.feature.user.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jajahome.R;
import com.jajahome.base.BaseActivity;
import com.jajahome.constant.Constant;
import com.jajahome.feature.user.adapter.DesignApplySelectPhotoAdapter;
import com.jajahome.model.CommitModel;
import com.jajahome.network.ApiImp;
import com.jajahome.network.UpBase64Req;
import com.jajahome.util.GlideEngine;
import com.jajahome.util.IdCheckUtil;
import com.jajahome.util.LoginUtil;
import com.jajahome.util.StringUtil;
import com.jajahome.util.T;
import com.jajahome.widget.ImageZoomUtils;
import com.jajahome.widget.SellerImg;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yalantis.ucrop.UCrop;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/10.
 */
public class CommitAct extends BaseActivity {

    public static String ORDERID = "orderId";
    public static String ORDERPRICE = "orderPrice";
    public static String PAYCOUNT = "payCount";

    @BindView(R.id.seller_img)
    SellerImg sellerImg;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.ibtn_back)
    ImageButton imgBtn;
    @BindView(R.id.account_name_et)
    EditText accNameT;
    @BindView(R.id.account_et)
    EditText accName;
    @BindView(R.id.commit_btn)
    Button commitBtn;


    private String mOrderId;
    private Double mOrderPrice;
    private int mPayCount;


    @Override
    protected int getViewId() {
        return R.layout.act_commit_act;
    }

    @Override
    protected void initEvent() {

        textView2.setText("转账上传");
        mOrderId = getIntent().getStringExtra(ORDERID);
        mOrderPrice = getIntent().getDoubleExtra(ORDERPRICE, 0);
        mPayCount = getIntent().getIntExtra(PAYCOUNT, 0);

        sellerImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission();
            }
        });

        imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        commitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkInput();
            }
        });

        accName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.length(); i++) {
                    if (i != 4 && i != 9 && i != 14 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 5 || sb.length() == 10 || sb.length() == 15) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }

                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            accName.setText(sb.subSequence(0, sb.length() - 1));
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    accName.setText(sb.toString());
                    accName.setSelection(index);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }


    /**
     * 获取读取内存卡，和 拍照的权限 Android 6.0 以后
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, DesignApplySelectPhotoAdapter.PERMISSON_STORGE);
        } else {
            selectPhoto();
        }
    }

    /**
     * 选择图片
     */
    private void selectPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(true)//列表是否显示拍照按钮
                .selectionMode(PictureConfig.SINGLE)
                .isEnableCrop(false)
                .scaleEnabled(false)
                .rotateEnabled(false)
                .isCompress(true)
                .minimumCompressSize(400)
                .compressQuality(70)
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    /**
     * 剪切图片完成回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // onResult Callback
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    path = selectList.get(0).getCompressPath();
                    if (!StringUtil.isEmpty(path)) {
                        sellerImg.setUrl(path);
                        Uri uri = Uri.parse("file:///" + path);
                        takeBit = getBitmapFromUri(uri);
                    }
                    break;
                default:
                    break;
            }
        }
    }
    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private String path;
    private Bitmap takeBit;

    private String encodeBase64File(String filePath) {

        try {
            File tmpFile = new File(filePath);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            bitmap = martix(bitmap);
            String voucher = ImageZoomUtils.Bitmap2StrByBase64(bitmap);
            return voucher;

        } catch (Exception e) {
            Log.e("tag", "读取视频出现异常");
        }
        return null;
    }


    private Bitmap martix(Bitmap bitmap) {

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        if (w > 2000 && h < 2000) {
            float scale = w / 2000;
            h = (int) (h / scale);
            w = 2000;
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        } else if (h > 2000 && w < 2000) {
            float scale = h / 2000;
            w = (int) (w / scale);
            h = 2000;
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        } else if (w > 2000 && h > 2000) {

            if (w > h) {
                float scale = w / 2000;
                h = (int) (h / scale);
                w = 2000;
                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
            } else if (w < h) {
                float scale = h / 2000;
                w = (int) (w / scale);
                h = 2000;
                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
            }
        }


        return bitmap;
    }


    private void upBase64() {

        UpBase64Req req = new UpBase64Req();
        req.setCmd(Constant.PAY_TRANSFORM_ACCOUNT);
        UpBase64Req.ContentBean bean = new UpBase64Req.ContentBean();
        bean.setOrder_id(mOrderId);
        bean.setOrder_price(mOrderPrice);
        bean.setPay_count(mPayCount);
        bean.setAccount(accName.getText().toString());
        bean.setAccountName(accNameT.getText().toString());
        bean.setImage(encodeBase64File(path));
        req.setContent(bean);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(req));
        RequestBody requestBodyl = RequestBody.create(MediaType.parse("application/session"), gson.toJson(LoginUtil.getInfo(mContext).getData().getSession()));
        mSubscription = ApiImp.get().pay_transform_account(requestBody, requestBodyl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommitModel>() {
                    @Override
                    public void onCompleted() {
                        dissmisProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dissmisProgressDialog();
                        showToast("提交失败");
                    }

                    @Override
                    public void onNext(CommitModel avatarModel) {
                        if (avatarModel.getStatus() == 0) {
                            T.showShort(mContext, "提交成功");
                            finish();
                        } else if (avatarModel.getStatus() == -22) {
                            T.showShort(mContext, avatarModel.getMessage());
                        }
                    }
                });

    }


    private void checkInput() {

        String accountName = accNameT.getText().toString();
        if (StringUtil.isEmpty(accountName)) {
            showToast("请输入户名");
            return;
        }
        String account = accName.getText().toString();
        if (StringUtil.isEmpty(account)) {
            showToast("请输入帐号");
            return;
        }

        char a;
        for (int i = 0; i < account.length(); i++) {
            a = account.charAt(i);
            if (IdCheckUtil.isNumer(a + "") || StringUtil.isEmpty(a + "")) {
                Log.i("--", "是数值");
            } else {
                showToast(R.string.input_num);
                return;
            }
        }

        if (takeBit == null) {
            showToast("请上传转帐凭证");
            return;
        }

        upBase64();
    }
}
